<?php
/**
 *
 * User: Jessica@aweb.wang
 * Date: 2023/3/10 14:50
 * Email: <1194323013@qq.com>
 *                            _ooOoo_
 *                           o8888888o
 *                           88" . "88
 *                           (| -_- |)
 *                           O\  =  /O
 *                        ____/`---'\____
 *                      .'  \\|     |//  `.
 *                     /  \\|||  :  |||//  \
 *                    /  _||||| -:- |||||-  \
 *                    |   | \\\  -  /// |   |
 *                    | \_|  ''\---/''  |   |
 *                    \  .-\__  `-`  ___/-. /
 *                  ___`. .'  /--.--\  `. . __
 *               ."" '<  `.___\_<|>_/___.'  >'"".
 *              | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *              \  \ `-.   \_ __\ /__ _/   .-` /  /
 *         ======`-.____`-.___\_____/___.-`____.-'======
 *                            `=---='
 *        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *                      Buddha Bless, No Bug !
 **/

namespace app\common\service;


use app\common\exception\BusinessException;
use app\common\exception\BusinessExceptionEnum;
use app\common\model\Applet;
use app\common\model\Department;
use app\common\model\Group;
use app\common\model\Premise;
use app\common\model\Role;
use app\common\model\User;
use app\common\model\UserRole;
use app\common\utils\TreeUtils;

class UserService
{
    public function login($data){


        $isCz=$this->selectByName($data['username']);
        if($isCz && md5($data['password'])==$isCz['password']){
            //可登录
            $info=$this->getFullInfo($isCz,$data['appid']);
            return $info;
        }else{
            throw new BusinessException(BusinessExceptionEnum::USERNAME_PASSWORD_WRONG);
        }
    }
    public function getFullInfo($user,$appid){
        $appinfo=Applet::where('appid',$appid)->find();
        $info=$user;
        $rolewhere[]=['isdel','=',0];
        $rolewhere[]=['status','=',1];
        $rolewhere[]=['id','in',json_decode($user['rolejson'],true)];
        $info['roleList']=Role::where($rolewhere)->field('id,name')->select();
        $depwhere[]=['isdel','=',0];
        $depwhere[]=['status','=',1];
        $depwhere[]=['id','in',json_decode($user['depjson'],true)];
        $info['depList']=Department::where($depwhere)->field('id,name')->select();
        $groupwhere[]=['isdel','=',0];
        $groupwhere[]=['status','=',1];
        $groupwhere[]=['id','in',json_decode($user['groupjson'],true)];
        $groupwhere[]=['applet_id','=',$appinfo['id']];
        $groupinfo=Group::where($depwhere)->field('id,name,pmsjson')->find();
//        print_r($groupinfo->toArray());
//        exit;
        if($groupinfo){
            $premisewhere[]=['is_del','=',0];
            $premisewhere[]=['status','=',1];
            $premisewhere[]=['id','in',json_decode($groupinfo['pmsjson'],true)];
            $premiseList=Premise::where($premisewhere)->select();
            $info['premiseTree']=TreeUtils::sort($premiseList);
        }else{
            $info['premiseTree']=[];
        }
        unset($info['password']);
        return $info;
    }
    public function update($data){
        $isCz=$this->selectByName($data['username']);
        if($isCz && $isCz['id']!=$data['id']){
            throw new BusinessException(BusinessExceptionEnum::USERNAME_ALREADY);
        }else{
            $where[]=['id','=',$data['id']];
            $madata['username']=$data['username'];
            $madata['avatar']=$data['avatar'];
            $madata['rolejson']=json_encode($data['rolejson']);
            $madata['groupjson']=json_encode($data['groupjson']);
            $madata['depjson']=json_encode($data['depjson']);
            if($data['password']){
                $madata['password']=md5($data['password']);
            }
            User::where($where)->update($madata);
            //角色差值比较并同步
            $insertIdArr=array_diff($data['rolejson'],$this->selectRoleArrByUid($data['id']));
            $deleteIdArr=array_diff($this->selectRoleArrByUid($data['id']),$data['rolejson']);
            $depdelwhere[]=['user_id','=',$data['id']];
            $depdelwhere[]=['role_id','in',$deleteIdArr];
            //将之前有现在没有的删除
            UserRole::where($depdelwhere)->delete();

            $userRole=new UserRole;
            $insertUserRoleList=[];
            foreach($insertIdArr as $key=>$value){
                $insertUserRoleItem['user_id']=$data['id'];
                $insertUserRoleItem['role_id']=$value;
                $insertUserRoleItem['creat_time']=date('Y-m-d H:i:s');
                array_push($insertUserRoleList,$insertUserRoleItem);
            }
            //将之前没有现在有的添加
            $userRole->saveAll($insertUserRoleList);
        }
    }
    public function selectRoleArrByUid($uid){
        $roleArr=[];
        $where[]=['user_id','=',$uid];
        $userRoleArr=UserRole::where($where)->select();
        foreach ($userRoleArr as $key=>$value){
            array_push($roleArr,$value['role_id']);
        }
        return $roleArr;
    }

    public function selectByName($name){
        $where[]=['username','=',$name];
        return User::where($where)->find();
    }
    public function create($data){
        $user=new User();
        $user->startTrans();
        try{
            $isCz=$this->selectByName($data['username']);
            if($isCz){
                throw new BusinessException(BusinessExceptionEnum::USERNAME_ALREADY);
            }else{
            //保存用户信息

                $user->username=$data['username'];
                $user->password=md5($data['password']);
                $user->avatar=$data['avatar'];
                $user->status=1;
                $user->is_del=0;
                $user->rolejson=json_encode($data['rolejson']);
                $user->groupjson=json_encode($data['groupjson']);
                $user->depjson=json_encode($data['depjson']);
                $user->create_time=date('Y-m-d H:i:s');
                $user->save();
                throw new BusinessException(BusinessExceptionEnum::USERNAME_ALREADY);
                //得到用户ID
                $uid=$user->id;
                //保存用户角色关系
                if($data['rolejson']){
                    //记录rolejson
                    $userRoleList=[];
                    $userRole=new UserRole;
                    foreach ($data['rolejson'] as $key=>$value){
                        $userRoleItem=[];
                        $userRoleItem['user_id']=$uid;
                        $userRoleItem['role_id']=$value;
                        $userRoleItem['create_time']=date('Y-m-d H:i:s');
                        array_push($userRoleList,$userRoleItem);
                    }
                    $userRole->saveAll($userRoleList);
                }
                //保存用户权限组关系
                if($data['groupjson']){
                    //记录groupjson
                    //todo...
                }
                //保存用户部门关系
                if($data['depjson']){
                    //记录depjson
                    //todo...
                }
            }


        }
        catch(\Exception $e){
            $user->rollback();
            throw new BusinessException(BusinessExceptionEnum::SYSTEM_ERROR);
        }
        $user->commit();
    }
    //删除
    public function del($id){
        $where[]=['id','=',$id];
        $data[]=['is_del','=',1];
        User::where($where)->update($data);
    }
    //获取列表
    public function list($page,$limit,$query){
        $data=User::where($query)->paginate([
            'list_rows'=> (string)$limit,
            'page' => (string)$page,
        ]);
        return $data;
    }
}